import json
import platform

import shutil
import subprocess
import time
from datetime import datetime
import os
from zoneinfo import ZoneInfo

import pytest

if __name__ == '__main__':
    # 获取当前时间,返回的是时间戳
    current_time = time.localtime(time.time())
    report = os.path.dirname(__file__) + os.sep + 'report'

    # clear last config_data
    allure_temp = os.path.dirname(__file__) + os.sep + 'temp-report'
    if os.path.exists(allure_temp):
        shutil.rmtree(allure_temp)
        os.makedirs(allure_temp)

    # 运行所有测试用例
    # pytest.main()
    pytest.main([
        'cases_ui/customer_management/test_customer_management_cases.py',
        'cases_ui/data_processing/test_data_processing_customized_rules_cases.py',
        'cases_ui/data_processing/test_data_processing_standard_rules_cases.py',
        'cases_ui/data_asset/test_data_origin.py',
        'cases_ui/data_asset/test_text_corpus.py',
        'cases_ui/data_asset/test_car_depot.py',
        'cases_ui/data_asset/test_resource_library.py',
        'cases_ui/label_manage/label_application.py',
        'cases_ui/label_manage/tag_library.py',
        'cases_ui/data_monitoring/test_data_push.py',
        'cases_ui/underlying_configuration/basic_configuration.py',
        'cases_ui/underlying_configuration/channel_allocation.py',
        'cases_ui/underlying_configuration/project_management.py',
        'cases_ui/data_asset/test_data_assets_cases.py',
        'cases_ui/account_management/test_account_management_cases.py',
        'cases_ui/role_management/test_role_management.py',
        'cases_ui/data_asset/test_public_domain_database.py'
    ])
    # pytest.main(['cases/test_at_watermark_cases.py'])
    # pytest.main(['cases/test_product_quality_cases.py', 'cases/test_quality_risk_insights_cases.py'])
    # 生成测试报告
    os.system(f"allure generate --clean {allure_temp} -o {report}")

    # 确定项目根目录的路径
    project_root = os.path.dirname(os.path.abspath(__file__))
    # 构建 summary.json 的完整路径
    summary_json_path = os.path.join(project_root, 'report/widgets/summary.json')
    # 步骤 1: 打开并读取 summary.json 文件内容
    with open(summary_json_path, 'r') as file:
        json_content = file.read()

        # 步骤 2: 解析 JSON 内容
        data = json.loads(json_content)

        # 步骤 3: 访问 'time' 对象中的 'start', 'stop' 和 'duration' 属性
        start_time = data['time']['start']
        stop_time = data['time']['stop']
        duration = data['time']['duration']  # 测试持续时间
        # 将毫秒转换为秒
        duration_in_seconds = duration / 1000.0

        # 计算小时、分钟和秒
        hours = int(duration_in_seconds // 3600)
        minutes = int((duration_in_seconds % 3600) // 60)
        seconds = int(duration_in_seconds % 60)

        # 格式化持续时间
        if hours > 0:
            # 如果有小时，则显示小时、分钟和秒
            formatted_duration = f"测试持续时间 (小时:分钟:秒): {hours}:{minutes:02d}:{seconds:02d}\n"
        elif minutes > 0:
            # 如果没有小时但有分钟，则显示分钟和秒
            formatted_duration = f"测试持续时间 (分钟:秒): {minutes}:{seconds:02d}\n"
        else:
            # 如果没有分钟，则只显示秒
            formatted_duration = f"测试持续时间 (秒): {seconds}\n"

        # 提取 statistic 对象
        statistic = data['statistic']

        # 获取各个统计值
        failed = statistic['failed']
        broken = statistic['broken']
        skipped = statistic['skipped']
        passed = statistic['passed']
        unknown = statistic['unknown']
        total = statistic['total']
        pass_rate = (passed / total) * 100 if total > 0 else 0
        # 将时间戳从毫秒转换为秒
        start_time_seconds = start_time / 1000.0
        stop_time_seconds = stop_time / 1000.0

        # 创建 Beijing 时区对象
        beijing_zone = ZoneInfo("Asia/Shanghai")  # 使用 Asia/Shanghai

        # 创建 datetime 对象，指定时区为 Beijing
        start_datetime = datetime.fromtimestamp(start_time_seconds, beijing_zone)
        stop_datetime = datetime.fromtimestamp(stop_time_seconds, beijing_zone)

        # 格式化为 24 小时制的日期和时间字符串
        start_time_str = start_datetime.strftime('%Y-%m-%d %H:%M:%S')
        stop_time_str = stop_datetime.strftime('%Y-%m-%d %H:%M:%S')

        # 打印结果
        # print(f"开始时间: {start_time_str}")
        # print(f"结束时间: {stop_time_str}")
        # print(f"测试持续时间 (秒): {duration / 1000.0}")
        #
        # # 打印各个统计值
        # print(f"总用例数: {total}")
        # print(f"通过用例数: {passed}")
        # print(f"失败用例数: {failed}")
        # print(f"故障用例数: {broken}")
        # print(f"跳过用例数: {skipped}")
        # print(f"未知用例数: {unknown}")
        # print(f"通过率: {pass_rate:.2f}%")

        # 构建结果文件的完整路径
        results_file_path = os.path.join(project_root, 'test_results.txt')

        with open(results_file_path, 'w') as file:
            file.write(f"开始时间: {start_time_str}\n")
            file.write(f"结束时间: {stop_time_str}\n")
            # file.write(f"测试持续时间 (秒): {duration / 1000.0}\n")
            file.write(formatted_duration)  # 测试持续时间
            file.write(f"总用例数: {total}\n")
            file.write(f"通过用例数: {passed}\n")
            file.write(f"失败用例数: {failed}\n")
            file.write(f"故障用例数: {broken}\n")
            file.write(f"跳过用例数: {skipped}\n")
            file.write(f"未知用例数: {unknown}\n")
            file.write(f"通过率: {pass_rate:.2f}%\n")

    file_path = report + '/index.html'
    if platform.system() == "Windows":
        print("You are using Windows")
        # List of arguments including the Edge executable name, flags, and file path:
        args = [
            r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe",  # 使用原始字符串
            '--disable-web-security',
            '--user-config_data-dir=C:\\edgeTemp',  # 使用双反斜杠
            file_path
        ]
        # Call subprocess.call with the arguments:
        subprocess.call(args)
    else:
        print("You are not using Windows")
        # open in a browser
        # webbrowser.open('file://' + report + '/index.html')
        os.system(f'open {file_path}')
    # print("wwwwwwwwwwwwww", file_path)
